<template>
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :span="6" :xs="24">
        <div class="mainbox-left">
          <div class="box-card">
            <!-- 搜索栏 -->
            <el-input
              v-model.trim="filterText"
              prefix-icon="el-icon-search"
              placeholder="请输入组织名称"
              maxlength="30"
              style="margin: 20px 0;"
            />
            <el-tree
              ref="tree"
              :empty-text="$store.getters.dataText"
              :style="{'--lightOpacity':lightTheme}"
              class="left-tree"
              :data="tree"
              :load="load"
              lazy
              :props="defaultProps"
              :default-expand-all="false"
              :expand-on-click-node="false"
              :highlight-current="true"
              :current-node-key="currentKey"
              :filter-node-method="filterNode"
              node-key="id"
              @node-click="handleNodeClick"
            />
          </div>
        </div>
      </el-col>
      <el-col :span="18" :xs="24" style="padding-left: 0px">
        <div class="none2-border3 userlist mainbox">
          <dt-table
            ref="tableRef"
            v-loading="loading"
            :table-opts="tableOpts"
            :pagination-data="{
              total:total,
              queryParams:filterForm
            }"
            :is-column-search="false"
            @pagination="pagination"
            @handleSelectionChange="handleSelectionChange"
            @searchReset="handleReset"
            @searchChange="handleQuery"
          >
            <template v-slot:toolbarBtn>
              <el-dropdown style="margin-left: 10px;">
                <el-button
                  v-permission="['USERMANAGE2_EXPORT_BUTTON']"
                  :disabled="tableOpts.tableData.length<=0"
                  size="medium"
                >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
                <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
                  <el-dropdown-item
                    @click.native="handleDownload('all')"
                  >导出所有</el-dropdown-item>
                  <el-dropdown-item
                    @click.native="handleDownload()"
                  >导出选中</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button v-permission="['USERMANAGE2_IMPORT_BUTTON']" style="margin-left: 10px" @click="handleImport">导入</el-button>
            </template>
            <template v-slot:authRealname="scope">
              <span :class="scope.param.authRealname=='Y'?'yesauth':'noauth'">{{ scope.param.authRealname=='Y'?'已实名认证':'未实名认证' }}</span>
            </template>
          </dt-table>
        </div>
      </el-col>
    </el-row>
    <dtDialog
      title="用户导入"
      :visible.sync="fileUploadVisible"
      width="620px"
      :is-loading="uploadLoading"
      @closeDialog="fileUploadVisible = false"
      @comfirmBtn="importDataSave"
    >
      <el-form slot="content">
        <div class="">
          <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="fileName" />
        </div>
      </el-form>
    </dtDialog>
    <dt-userDialog ref="userDialogRef" />


      <!-- 用户授权页面 -->
      <el-dialog
          title="用户授权页面(应用系统仅有未授权的显示)"
          :visible.sync="authVisable"
          width="800px"
        >
        <el-form :model="dialogForm" ref="dialogForm" label-width="80px">
            <el-row>
              <el-col :span="11">
                <el-form-item label="用户名">
                  <el-input v-model="dialogForm.realName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="账号">
                  <el-input v-model="dialogForm.account" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="性别">
                  <el-input v-model="dialogForm.sex=='M'?'男':'女' " disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="身份证号">
                  <el-input v-model="dialogForm.idCard" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table :data="gridData" border stripe size="mini" height="300" v-loading="dialogLoading" :header-cell-style="{ backgroundColor: '#f2f2f2' }">
            <el-table-column property="appName" label="业务系统" align="center" />
            <el-table-column property="operate" label="操作" align="center" >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="appAuthUser(scope.row)"
                size="mini">授权</el-button>
              </template>
            </el-table-column>
          </el-table>


          <span slot="footer" class="dialog-footer">
            <el-button @click="authVisable = false">关闭</el-button>
          </span>
        </el-dialog>

  </div>
</template>

<script>
import hrOrganizationApi from '@/framework/api/userCenter/hrOrganization'
import DtUserDialog from './components/dt-userDialog'
import sysUserApi from '@/framework/api/userCenter/sysUser'
import businessUserApi from '@/api/user/userApi'

export default {
  name: 'UserManage',
  dicts: ['user_status'],
  components: { DtUserDialog },
  data() {
    return {
      filterText: '',
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentKey: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      filterForm: {
        account: '',
        realName: '',
        orgId: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        tableData: [],
        rowKey: 'userId',
        toolbarBtn: [
          {
            label: '新增',
            permission: ['USERMANAGE2_ADD_BUTTON'],
            type: 'primary',
            click: (type) => {
              this.createUserInfo(type)
            }
          }
        ],
        // 表格第一列
        firstTableCol: {
          select: true,
          width: 55,
          type: 'selection'
        },
        tableCol: [
          {
            prop: 'account',
            label: '账号',
            show: true,
            search: true
          },
          {
            prop: 'realName',
            label: '姓名',
            show: true,
            search: true
          },
          // {
          //   prop: 'positionName',
          //   label: '岗位',
          //   show: true
          // },
          // {
          //   prop: 'phone',
          //   label: '联系电话',
          //   show: true
          // },
          {
            prop: 'statusFlag',
            label: '启用状态',
            type: 'switch',
            show: true,
            search: true,
            activeValue: 1,
            inactiveValue: 2,
            switchChange: (row, value) => { return this.statusChange(row) },
            formatter: () => {
              return this.dict.type.user_status
            },
            disabledChange: (row) => { return row.superAdminFlag == 'Y' || row.tenantAdminFlag == 'Y' }
          },
          {
            prop: 'authRealname',
            label: '是否实名认证',
            show: true,
            width: 150,
            slotName: 'authRealname'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            show: true
          }
        ],
        operator: {
          width: 400,
          operatorBtn: [
            {
              'text': '修改',
              permission: ['USERMANAGE2_UPDATE_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.editUserInfo(row) }
            },
            {
              'text': '授权业务系统',
              permission: ['USERMANAGE2_APP_AUTH'],
              size: 'small',
              click: (row) => { return this.appAuthUserDialog(row) }
            },
            {
              'text': '重置密码',
              permission: ['USERMANAGE2__RESET_PASSWORD_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.resetPassWord(row) }
            },
            {
              'text': '删除',
              permission: ['USERMANAGE2_DEL_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.removeUser(row) },
              disabledChange: (row) => { return row.superAdminFlag == 'Y' || row.tenantAdminFlag == 'Y' }
            }
          ]
        }
      },
      orgName: '',
      fileUploadVisible: false,
      uploadLoading: false,
      handleImportTemplate: sysUserApi.downloadTemplate,
      multipleSelection: [],
      fileName: '用户信息',
      authUserId: null,
      authAppId: null,
      authVisable: false,
      gridData: [],
      dialogLoading:false,
      dialogForm:{},
    }
  },
  computed: {
    lightTheme() {
      return this.$store.state.settings.theme + '19'
    }
  },
  watch: {
    filterText(val) {
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: val }).then((res) => {
        const data = res.data.map((item, index) => {
          item.orgId = item.id
          item.orgName = item.name
          return item
        })
        this.tree = data
      })
    },
    fileUploadVisible: {
      handler(n, o) {
        if (!n) {
          this.$nextTick().then(() => {
            this.$refs.dtImportFileRef.fileList = []
          })
        }
      }
    }
  },
  created() {
    this.initTree()
    console.info(this.$store.getters.name);
    console.info(this.$store.getters.roles);
  },
  methods: {
    appAuthUserDialog(row){
      this.dialogForm=row;
      this.authUserId=row.userId;
      this.authVisable=true;
      this.qryNoHasUserApp();
    },
    qryNoHasUserApp(){
      this.dialogLoading=true;
      businessUserApi.qryNoHasUserApp(this.authUserId).then(res=>{
        this.gridData=res.data
        this.dialogLoading=false;
      }).catch(res=>{
        this.$message.error(res.message)
        this.dialogLoading=false;
      })
    },
    appAuthUser(row){
      this.dialogLoading=true;
      businessUserApi.appAuthUser({systemId: row.appId, userId:this.authUserId}).then(res=>{
        this.qryNoHasUserApp();
      }).catch(res=>{
        this.$message.error(res.message)
        this.dialogLoading=false;
      })
    },
    // 获取页面列表
    getList() {
      this.loading = true
      this.filterForm.orgId = this.selectedOrg.id
      this.filterForm.containSelf = false
      sysUserApi.fetchPage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.sysUserListLength = res.data.rows.length
        this.loading = false
      })
    },
    // 表单重置
    reset() {
      this.form = {
      }
      this.resetForm('queryForm')
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.filterForm = { ...this.filterForm, ...formModel }
      // this.filterForm = Object.assign(this.filterForm, formModel)
      this.filterForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        account: '',
        realName: '',
        statusFlag: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.$refs.userManageConfigRef.userManage(row, 'update')
    },
    statusChange(v, row, index) {
      businessUserApi.changeStatus({
        statusFlag: v.statusFlag,
        userId: v.userId
      }).then((res) => {
        this.$dtMessage({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(res => {
        this.getList()
      })
    },
    createUserInfo() {
      this.$refs.userDialogRef.openDialog(this.selectedOrg, 'create', '')
    },
    editUserInfo(row) {
      this.$refs.userDialogRef.openDialog(this.selectedOrg, 'update', row)
    },
    resetPassWord(row) {
      const that = this
      this.$confirm('是否确认重置密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sysUserApi.resetPwd(row).then((res) => {
          that.getList()
          that.$dtMessage({
            message: '重置成功',
            type: 'success'
          })
        })
      })
    },
    removeUser(row) {
      this.$dtMessageBox({ title: '提示', message: '确定要删除“' + row.account + '”吗?', type: 'warning' }).then(() => {
        businessUserApi.delete({ userId: row.userId }).then(res => {
          this.getList()
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
          // 解决勾选了一个数据后，再删除该数据，然后再进行导出的时候导出不提示"至少勾选一条数据"，并且可以导出导出的表为空的bug
          this.multipleSelection.forEach((item, index, multipleSelection) => {
            if (item.userId === row.userId) {
              multipleSelection.splice(index, 1)
              return multipleSelection
            } else {
              return multipleSelection
            }
          })
          if (this.multipleSelection.length == 0) {
            this.$refs.tableRef.$refs.table.clearSelection()
          }
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    // // 懒加载
    load(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
        return
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const data = res.data.map((item, index) => {
          this.selectedOrg = res.data[0]
          this.currentKey = res.data[0].id

          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(res.data[0].id)
          })
          return item
        })
        resolve(data)
      })
    },
    loadPopover(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const data = res.data
        resolve(data)
      })
    },
    // 左侧树结构
    handleNodeClick(data) {
      this.filterForm.orgId = data.id
      this.selectedOrg = data
      this.currentKey = this.selectedOrg.id
      this.handleQuery()
    },
    // 获取左侧组织树
    initTree() {
      const that = this
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0 }).then((res) => {
        that.tree = res.data
        this.selectedOrg = res.data[0]
        this.currentKey = res.data[0].id
        this.getList()
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(res.data[0].id)
        })
      })
    },
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        this.showScreenLoading()
        sysUserApi.exportAllUser().then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '用户信息' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map(res => {
          return res.userId
        }).join(',')
        con = {
          userIds: ids,
          account: this.filterForm.account,
          realName: this.filterForm.realName,
          orgId: this.currentKey
        }
        this.showScreenLoading()
        sysUserApi.exportUser(con).then(res => {
          if (this.tableOpts.tableData == null) {
            this.$dtMessage({
              title: '失败',
              message: res.message,
              type: 'error',
              duration: 2000
            })
          } else {
            const blob = new Blob([res.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const objectUrl = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = objectUrl // 指定下载链接
            a.download = '用户信息' // 指定下载文件名
            a.click()
            URL.revokeObjectURL(a.href) // 释放URL对象
            this.hideScreenLoading()
          }
        }).catch(res => {
          this.hideScreenLoading()
        })
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    pagination() {
      this.getList()
    },
    handleImport() {
      this.fileUploadVisible = true
    },
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      sysUserApi.uploadFile(formData).then(async(res) => {
        this.uploadLoading = true
        this.fileUploadVisible = false
        if (res.data.errorDownloadPath) {
          this.$alert('<div> <div class="title">' + res.data.tip + '</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败用户信息</span> </div> </div>', '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert('<div> <div class="title">' + res.data.tip + '导入完成', {
            dangerouslyUseHTMLString: true
          })
        }
        this.getList()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function() {
          window.location.href = res.data.errorDownloadPath
        }
        this.uploadLoading = false
      }).catch(res => {
        this.uploadLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.yesauth{
  padding:0 10px;
  background:#a1f091;
  color: #219f08;
  border-radius: 5px;
  height: 30px;
  line-height: 30px;
  display: inline-block;
}
.noauth{
  padding:0 10px;
  background:#f4a0a0;
  color: #f30404;
  border-radius: 5px;
  height: 30px;
  line-height: 30px;
  display: inline-block;
}
</style>
